<template>
  <div class="user-form-container" v-loading="loading">
    <div class="header">
      <el-page-header @back="goBack" :title="'返回用户列表'" :content="isEdit ? '编辑用户' : '创建用户'" />
    </div>

    <el-card class="form-card">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatarRequest"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="userForm.roles" multiple placeholder="请选择角色">
            <el-option v-for="role in roleOptions" :key="role.value" :label="role.label" :value="role.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="UserStatus.ENABLED">启用</el-radio>
            <el-radio :label="UserStatus.DISABLED">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getUserDetail, createUser, updateUser, uploadAvatar } from '@/api/system/user.ts';
import { getAllRoles } from '@/api/user-management/role';
import { UserStatus, UserRole, type UserRequest, type Role } from '@/types/system/user.ts';
import type { FormInstance, UploadRequestOptions } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userId = ref(route.query.id as string);
const isEdit = computed(() => !!userId.value);

// 表单数据
const userFormRef = ref<FormInstance>();
const loading = ref(false);
const userForm = reactive<UserRequest>({
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  avatar: '',
  status: UserStatus.ENABLED,
  roles: []
});

// 角色选项
const roles = ref<Role[]>([]);
const roleOptions = computed(() => {
  return Object.values(UserRole).map(role => ({
    value: role,
    label: getRoleName(role)
  }));
});

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 获取角色名称
const getRoleName = (roleCode: string) => {
  switch (roleCode) {
    case UserRole.ADMIN:
      return '管理员';
    case UserRole.DEVELOPER:
      return '开发者';
    case UserRole.USER:
      return '普通用户';
    default:
      return roleCode;
  }
};

// 获取用户详情
const getUserInfo = async () => {
  if (!userId.value) return;

  loading.value = true;
  try {
    const res = await getUserDetail(parseInt(userId.value));
    const user = res.data;
    userForm.id = user.id;
    userForm.username = user.username;
    userForm.nickname = user.nickname;
    userForm.email = user.email;
    userForm.phone = user.phone;
    userForm.avatar = user.avatar;
    userForm.status = user.status;
    userForm.roles = user.roles;
  } catch (error) {
    console.error('获取用户详情失败', error);
    ElMessage.error('获取用户详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取所有角色
const getRoles = async () => {
  try {
    const res = await getAllRoles();
    roles.value = res.data;
  } catch (error) {
    console.error('获取角色列表失败', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 返回列表
const goBack = () => {
  router.push('/user-management/users');
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (isEdit.value) {
          await updateUser(userForm);
          ElMessage.success('更新用户成功');
        } else {
          await createUser(userForm);
          ElMessage.success('创建用户成功');
        }
        goBack();
      } catch (error) {
        console.error('提交用户表单失败', error);
        ElMessage.error('提交用户表单失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 上传头像前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 自定义上传请求
const uploadAvatarRequest = async (options: UploadRequestOptions) => {
  try {
    const res = await uploadAvatar(options.file as File);
    userForm.avatar = res.data;
    ElMessage.success('上传头像成功');
  } catch (error) {
    console.error('上传头像失败', error);
    ElMessage.error('上传头像失败');
  }
};

onMounted(() => {
  getRoles();
  if (isEdit.value) {
    getUserInfo();
  }
});
</script>

<style scoped>
.user-form-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
